use crate::websockt::WebSocketParseError;

use super::WebSocketOpCode;


#[derive(Debug, Clone, PartialEq)]
pub enum WebSocketPayload {
    Text(String),
    Binary(Vec<u8>),
    Close,
    Ping,
    Pong,
    Raw(Vec<u8>),
}

impl WebSocketPayload {
    pub fn to_bytes(&self) -> Vec<u8> {
        match self {
            WebSocketPayload::Text(s) => s.as_bytes().to_vec(),
            WebSocketPayload::Binary(b) => b.clone(),
            WebSocketPayload::Close => Vec::new(),
            WebSocketPayload::Ping => Vec::new(),
            WebSocketPayload::Pong => Vec::new(),
            WebSocketPayload::Raw(b) => b.clone(),
        }
    }

    pub fn from(opcode: WebSocketOpCode, bytes: Vec<u8>) -> Result<Self, WebSocketParseError> {
        match opcode {
            WebSocketOpCode::Text => {
                let s = std::str::from_utf8(&bytes)?;
                Ok(WebSocketPayload::Text(s.to_string()))
            }
            WebSocketOpCode::Binary => Ok(WebSocketPayload::Binary(bytes)),
            WebSocketOpCode::Close => Ok(WebSocketPayload::Close),
            WebSocketOpCode::Ping => Ok(WebSocketPayload::Ping),
            WebSocketOpCode::Pong => Ok(WebSocketPayload::Pong),
            WebSocketOpCode::Other(_) => Ok(WebSocketPayload::Raw(bytes)),
        }
    }
}
